#include "socket.hpp"
#include "protocol.hpp"
#include<sys/wait.h>


using server_t = std::function<void(std::shared_ptr<Socket>&,const InetAddr&)>;

class TcpServer
{
public:
    TcpServer(uint16_t port,server_t server)
    :_port(port)
    ,_isrunning(false)
    ,_listensocket(std::make_unique<TcpSocket>())  
    ,_server(server)
    {
        _listensocket->BindTcpServerSocket(_port);
    }

    ~TcpServer()
    {

    }

    void Start()
    {
        _isrunning = true;
        while(_isrunning)
        {
            InetAddr client;
            std::shared_ptr<Socket> sockfd =  _listensocket->SocketAccept(client);
            pid_t id = fork();
            if(id == 0)
            {
                pid_t pid = fork();
                if(pid == 0)
                {
                    _server(sockfd,client);
                    std::exit(0);
                }
                std::exit(0);
            }
            ::waitpid(id,nullptr,0);
        }
    }


private:
    uint16_t _port;
    bool _isrunning;
    std::unique_ptr<Socket> _listensocket;
    server_t _server;
};
